package algorithm.practice;

import java.util.Arrays;

/**
 * @description: 直接插入排序和shell排序
 * @author: Fesine
 * @createTime:2017/8/1 8:56
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/8/1 8:56
 */
public class InsertionSortPractice {

    /**
     * 直接插入法
     * @param sorted
     */
    public static void insertionSort(int[] sorted) {
        for (int i = 1; i < sorted.length; i++) {
            for (int j = i; j > 0; j--) {
                if (sorted[j] < sorted[j-1]){
                    int tmp = sorted[j-1];
                    sorted[j-1] = sorted[j];
                    sorted[j]= tmp;
                }
            }
        }
    }

    public static void shellInsertionSort(int[] sorted) {
        int n = sorted.length;
        int d = n /2;
        while (d > 0) {
            for (int i = d; i < n; i++) {
                int j =i - d; //依次递增
                    while (j >= 0 && sorted[j] > sorted[j + d]) {
                        int tmp = sorted[j];
                        sorted[j] = sorted[j+d];
                        sorted[j+d]=tmp;
                        j = j -d;
                    }
                d = d /2;
            }
        }
    }

    public static void main(String[] args) {
        int[] a = {3, 6, 4, 2, 11, 10, 5};
        insertionSort(a);
        System.out.println(Arrays.toString(a));
        System.out.println();
        a = new int[]{3, 6, 4, 2, 11, 10, 5};
        shellInsertionSort(a);
        System.out.println(Arrays.toString(a));
    }
}
